package top.huxy.boot.config.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.huxy.boot.config.Constant;
import top.huxy.boot.exception.NoCredentialsException;
import top.huxy.boot.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname AdminControllerInterceptor
 * @Description AdminControllerInterceptor
 * @Date 2021/8/30 19:44
 * @Created by huxy
 */
public class AdminControllerInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 从请求头中获取token，验证token
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) return true;

        Object adminObject = request.getAttribute(Constant.ADMIN_ATTRIBUTE_NAME);
        if (adminObject != null) return true;

        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (Constant.ADMIN_TOKEN_NAME.equals(name)) {
                    String token = cookie.getValue();
                    if (StringUtils.isEmpty(token)) throw new NoCredentialsException("无权访问");
                    Object admin = redisTemplate.opsForValue().get(token);
                    if (admin == null) throw new NoCredentialsException("登录凭证过期");

                    request.setAttribute(Constant.ADMIN_ATTRIBUTE_NAME, admin);
                    return true;
                }
            }
        }else{
            throw new NoCredentialsException("未携带凭证");
        }
        return false;
    }
}
